#include "GameObjectWrap.h"
#include "../render_v1.h"
#include "TransformWrap.h"

namespace hxe {
    static int newObject(lua_State *L)
    {
        const char* name = lua_tostring(L, 1);
        GameObject* t = new GameObject(name);
        HLuaInst->push(t, GameObjectWrap::metaRef);
        t->drop();
        return 1;
    }

    static int getTransform(lua_State *L)
    {
        GameObject* g = (GameObject*)(HLuaInst->fastGetCObj(1));
        Transform* t = g->transform;
        if (t == nullptr)
        {
            return 0;
        }
        else
        {
            HLuaInst->push(t, TransformWrap::metaRef);
            return 1;
        }
    }

    static int setLayer(lua_State *L)
    {
        GameObject* g = (GameObject*)(HLuaInst->fastGetCObj(1));
        int layer = (int)lua_tointeger(L, 2);
        g->layer = layer;
        return 0;
    }
}
int hxe::GameObjectWrap::metaRef = 0;

int hxe::GameObjectWrap::loadWrap(lua_State *L)
{
    lua_newtable(L);

    // gc
    lua_pushstring(L, "__gc");
    lua_pushcclosure(L, HLuaInst->gcObject, 0);
    lua_rawset(L, -3);

    // call
    lua_pushstring(L, "new");
    lua_pushcclosure(L, newObject, 0);
    lua_rawset(L, -3);

    // set
    lua_pushstring(L, "__newindex");
    lua_newtable(L);
    lua_pushcclosure(L, HLuaInst->objNewIndexer, 1);
    lua_rawset(L, -3);

    // get
    lua_pushstring(L, "__index");
    lua_newtable(L);

    lua_pushstring(L, "GetTransform");
    lua_pushcclosure(L, getTransform, 0);
    lua_rawset(L, -3);

    lua_pushstring(L, "SetLayer");
    lua_pushcclosure(L, setLayer, 0);
    lua_rawset(L, -3);

    lua_pushcclosure(L, HLuaInst->objIndexer, 1);
    lua_rawset(L, -3);

    lua_pushvalue(L, -1);
    lua_setglobal(L, "GameObject");
    metaRef = luaL_ref(L, LUA_REGISTRYINDEX);

    return 0;
}
